﻿using System.ComponentModel.Composition;
using System.Text;
using AppsGenerator.Generators;
using AppsGenerator.Models;
using AppsGenerator.Utils;
using DBBuilder.DBDataStructure;

namespace AppsGenerator.WebGenerators.WebControllerGenerator
{
    /// <summary>
    /// The algorithm for generating Insert method of common controller
    /// </summary>
    [Export(typeof(InsertControllerItemByCommonAlgorithm))]
    public class InsertControllerItemByCommonAlgorithm : BaseGenerator, IInsertControllerItemAlgorithm
    {
        /// <summary>
        /// The method to generate Insert contents of common controller
        /// </summary>
        /// <param name="item">The item which extracted from template file</param>
        /// <param name="tbl">The datasource for generating</param>
        /// <returns></returns>
        public string GenerateContents(Item item, Table tbl)
        {
            var contents = new StringBuilder(BaseConsts.MAX_BYTES);

            foreach (Attribute attr in tbl.Attributes)
            {
                if (!attr.IsIdentify)
                {
                    contents.Append(BaseConsts.TAB3).AppendLine(string.Format("var {0} = Forms.Get(\"{1}\");",
                                                                              attr.Name.ToLowerFirstCharacter(),
                                                                              attr.Name));
                }
            }

            contents.Append(BaseConsts.TAB3).AppendLine(string.Format("var item = new {0}", tbl.Name));
            contents.Append(BaseConsts.TAB3).AppendLine("{");

            foreach (var attr in tbl.Attributes)
            {
                if (!attr.IsIdentify)
                {
                    contents.Append(BaseConsts.TAB4).AppendLine(string.Format("{0} = {1},", attr.Name,
                                                                              this.BuildParsingData(attr)));
                }
            }

            contents.Append(BaseConsts.TAB3).AppendLine("};");

            string MainForeignKey;
            if (tbl.IsTableWithMainForeignKey(out MainForeignKey))
            {
                contents.Append(BaseConsts.TAB3).AppendLine(string.Format("var {0} = item.{1};", MainForeignKey,
                                                                          MainForeignKey));
            }

            return contents.ToString().TrimStart().TrimEnd();
        }
    }
}
